//
//  AppDelegate.m
//  Pocket Doctor alpha version
//
//  Created by Sherif, Yin, Taylor, Jacob, Anna, Mike on 11-10-25.
//  Copyright (c) 2011 __Sytjam__. All rights reserved.
//
//Class Description: Things that happen when the application is launched.
//
//Known Bugs: none.
//
//missing features : some troubles with notification.
//add "did you know" alert or something throughout the app.
//

#import "AppDelegate.h"
#import "Navigator.h"
#import "sqlite3.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewChooser, dbPointer;

int try = 0; //keep track of alerts

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    application.applicationIconBadgeNumber = 0; //resets the notifications to 0 when application is launched.
    
/*    UILocalNotification *localNotif =
    [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotif) {
        
       // NSString *itemName = [localNotif.userInfo objectForKey:@"id"];
        
        // this was launched by a notification
        NSString *medName = [localNotif.userInfo objectForKey:@"medName"];
       // NSNumber *medID = [localNotif.userInfo objectForKey:@"id"];
        NSString *instructions = [localNotif.userInfo objectForKey:@"instructions"];
        NSString *message = [[NSString alloc]initWithFormat:@"It's time to take %@,\nInstructions: %@", medName, instructions];
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Pocket Doctor" message:message delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
    }*/
    
    [self.window addSubview:viewChooser.view];

    [self.window makeKeyAndVisible];
    return YES;
}

/*This will handle receiving notifications while the application is active*/
- (void)application:(UIApplication* )app didReceiveLocalNotification:(UILocalNotification *)notification{
    
    NSString *medName = [notification.userInfo objectForKey:@"medName"];
    NSString *instructions = [notification.userInfo objectForKey:@"instructions"];
    NSString *message = [[NSString alloc]initWithFormat:@"It's time to take %@,\nInstructions: %@", medName, instructions];
    
    app.applicationIconBadgeNumber = notification.applicationIconBadgeNumber-1;
    
    if(try == 0){
        if(app.applicationState == UIApplicationStateActive){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:medName message:message delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            
            [alert show];
            [alert release];
        }
        try++; //try makes sure that no 2 notifications are triggered.
    }
    
}

/*This function will avoid alerts appearing twice*/
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        try = 0; //try is reset when the alert is dismissed
    }
    
}

/* Load up an existing database file, if one exists. If not, create a new file and call createDB which forms the proper schema.*/
- (void)initDB{
    
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString * databasePath = [documentsDirectory stringByAppendingPathComponent:@"PocketDoctor.db"];
    //NOTE: during development, this file will be at path /Users/sherifnosseir/Library/Application Support/iPhone Simulator/5.0/Applications/2C2A9C75-1076-469B-9541-AD1A89CC2E4B/Documents
    if(![fileManager fileExistsAtPath:databasePath]){
        sqlite3_open([databasePath UTF8String], &dbPointer);
        // The file doesn't exist, let's create the database anew.
        
       [self createDB]; 
        
        //   UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Unsuccessful" message:@"Cannot open database" delegate:nil cancelButtonTitle:@"Done" otherButtonTitles: nil];
        //  [alert show];
        // [alert release];
        
    }else{ /*file exists*/
        const char * dbPath = [databasePath UTF8String];
        sqlite3_open(dbPath, &dbPointer);
    }
}

// Create the appropriate tables in the database.
- (void)createDB{
        const char *sql_createdb = "CREATE TABLE Date (id integer PRIMARY KEY AUTOINCREMENT, associated_medicine integer, time TEXT NOT NULL, FOREIGN KEY(associated_medicine) REFERENCES Medicine(id), UNIQUE (associated_medicine, time)); \
        CREATE TABLE Emergency_Numbers (id INTEGER PRIMARY KEY AUTOINCREMENT, contact_name text NOT NULL, contact_number text NOT NULL); \
        CREATE TABLE Image (id INTEGER PRIMARY KEY AUTOINCREMENT, associated_medicine integer NOT NULL, image_file_path text NOT NULL, FOREIGN KEY(associated_medicine) REFERENCES Medicine(id)); \
        CREATE TABLE Medicine (id integer primary key autoincrement, medicine_type text, medicine_name text, refillable bool, instruction text, dosage_per_serving double, dosage_type text, quantity_remaining double); \
        CREATE TABLE Security (id integer primary key unique, passcode integer, passcode_hint text, secret_question text, secret_answer text); \
        CREATE TABLE Voice (id INTEGER PRIMARY KEY AUTOINCREMENT, associated_medicine integer NOT NULL, voice_file_path text NOT NULL, FOREIGN KEY(associated_medicine) REFERENCES Medicine(id)); \
        CREATE TABLE Settings (id integer primary key unique, emergency_contact text, clock_setting integer, date_setting integer, day_setting integer, email_address text, refillsound text DEFAULT 'default', alertsound text DEFAULT 'default', refillreminder integer DEFAULT 25); \
        CREATE TABLE MedicineLog (medicine_name text, log_change text, status text, time text NOT NULL)";
        sqlite3_exec(dbPointer, sql_createdb, NULL, NULL, NULL); // todo: if there is an error, handle it
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    application.applicationIconBadgeNumber = 0; //resets the notifications to 0 when application is resumed.
    
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
    sqlite3_close(dbPointer);
}

@end
